package com.xiaozhen.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.common.core.domain.system.SysRole;
import com.xiaozhen.common.core.domain.system.SysUserRole;
import com.xiaozhen.common.core.domain.system.vo.SysUserListVo;
import com.xiaozhen.common.core.domain.system.queryParams.SysUserQueryParam;
import com.xiaozhen.common.core.exception.CustomException;
import com.xiaozhen.common.core.utils.StringUtils;
import com.xiaozhen.common.core.utils.UserUtils;
import com.xiaozhen.system.dao.SysUserDao;
import com.xiaozhen.system.dao.SysUserRoleDao;
import com.xiaozhen.system.service.SysUserService;
import com.xiaozhen.common.core.domain.system.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/8/5 9:40
 * @description:
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public SysUser selectByUsername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        SysUser sysUser = sysUserDao.selectOne(queryWrapper);
        return sysUser;
    }

    @Override
    public Page<SysUserListVo> selectUserList(Page<SysUser> page, SysUserQueryParam queryParam) {
        Page<SysUserListVo> userListPage = sysUserDao.selectUserList(page, queryParam);
        return userListPage;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Integer updateUserStatus(SysUser sysUser) {
        return sysUserDao.updateById(sysUser);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return sysUserDao.selectById(userId);
    }

    @Override
    public Boolean checkUserNameUnique(String userName) {
        int count = sysUserDao.checkUserNameUnique(userName);
        if (count == 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserDao.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserDao.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Integer insertUser(SysUser user) {
        int rows = sysUserDao.insert(user);
        // 新增用户岗位关联
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    @Transactional(rollbackFor = {Exception.class})
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            Long userId = user.getUserId();
            List<SysUserRole> userRoleList = new ArrayList<>();
            for (Long roleId : roles) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                userRoleList.add(sysUserRole);
            }
            sysUserRoleDao.batchUserRole(userRoleList);
        }
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && UserUtils.isAdmin(user.getUserId())) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    public void checkUserAllowed(Long userId) {
        if (StringUtils.isNotNull(userId) && UserUtils.isAdmin(userId)) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Integer updateUser(SysUser user) {
        int rows = sysUserDao.updateById(user);
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", user.getUserId());
        sysUserRoleDao.delete(userRoleQueryWrapper);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        // 新增用户与岗位管理
        return rows;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Integer deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(userId);
        }
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("user_id", userIds);
        sysUserRoleDao.delete(userRoleQueryWrapper);
        // 删除用户与岗位关联
        return sysUserDao.deleteBatchIds(Arrays.asList(userIds));
    }

    @Override
    public String selectUserRoleGroup(Long userId) {
        List<SysRole> list = sysUserRoleDao.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public int resetUserPwd(Long userId, String password) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setPassword(password);
        return sysUserDao.updateById(sysUser);
    }

    @Override
    public int updateUserAvatar(Long userId, String url) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setAvatar(url);
        return sysUserDao.updateById(sysUser);
    }
}
